package com.iwhalecloud.citybrain.flow.platform.manager.infrastructure.repository;

import java.util.Date;
import java.util.List;
import java.util.Objects;

import com.iwhalecloud.citybrain.flow.platform.manager.domain.model.FlowMultiInstanceTaskTraceVo;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.repository.FlowMultiInstanceTaskTraceRepository;
import com.iwhalecloud.citybrain.flow.platform.manager.infrastructure.entities.FlowMultiInstanceTaskTrace;
import com.iwhalecloud.citybrain.flow.platform.manager.infrastructure.entities.FlowMultiInstanceTaskTraceExample;
import com.iwhalecloud.citybrain.flow.platform.manager.infrastructure.mapper.FlowMultiInstanceTaskTraceDAO;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author lilh
 * @date 2019-09-20 10:24
 */
@Service
public class FlowMultiInstanceTaskTraceRepositoryImpl implements FlowMultiInstanceTaskTraceRepository {

    @Autowired
    private FlowMultiInstanceTaskTraceDAO flowMultiInstanceTaskTraceDAO;

    @Override
    public int insertMultiInstanceTaskTrace(FlowMultiInstanceTaskTraceVo vo) {
        vo.setCreateTime(new Date());
        vo.setUpdateTime(new Date());
        FlowMultiInstanceTaskTrace entity = new FlowMultiInstanceTaskTrace();
        BeanUtils.copyProperties(vo, entity);
        flowMultiInstanceTaskTraceDAO.insertSelective(entity);
        return entity.getId();
    }

    @Override
    public FlowMultiInstanceTaskTraceVo getByRootExecutionId(String rootExecutionId) {
        FlowMultiInstanceTaskTraceExample query = new FlowMultiInstanceTaskTraceExample();
        query.createCriteria().andRootExecutionIdEqualTo(rootExecutionId);
        List<FlowMultiInstanceTaskTrace> flowMultiInstanceTaskTraces = listMultiInstanceTaskTraces(query);
        if (CollectionUtils.isNotEmpty(flowMultiInstanceTaskTraces)) {
            return convert(flowMultiInstanceTaskTraces.get(0));
        }
        return null;
    }

    private List<FlowMultiInstanceTaskTrace> listMultiInstanceTaskTraces(FlowMultiInstanceTaskTraceExample query) {
        return flowMultiInstanceTaskTraceDAO.selectByExample(query);
    }

    @Override
    public int updateMultiInstanceTaskTrace(FlowMultiInstanceTaskTraceVo vo) {
        FlowMultiInstanceTaskTrace entity = new FlowMultiInstanceTaskTrace();
        BeanUtils.copyProperties(vo, entity);
        return flowMultiInstanceTaskTraceDAO.updateByPrimaryKeySelective(entity);
    }

    private FlowMultiInstanceTaskTraceVo convert(FlowMultiInstanceTaskTrace entity) {
        if (Objects.isNull(entity)) {
            return null;
        }

        FlowMultiInstanceTaskTraceVo result = new FlowMultiInstanceTaskTraceVo();
        BeanUtils.copyProperties(entity, result);
        return result;
    }
}
